﻿using System.ServiceModel.Dispatcher;
using System.Web;
using GlimpseWcf.Core;

namespace GlimpseWcf.Client
{
    public class WcfClientMessageInspector : IClientMessageInspector, IParameterInspector
    {
        private readonly HttpContextBase _context;
        private WcfGlimpseResponse _response;

        public WcfClientMessageInspector(HttpContextBase context)
        {
            _context = context;
        }

        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            _response = WcfGlimpseResponseMessageHeader.ReadHeader(reply);
        }

        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            request.Headers.Add(new CookieMessageHeader(_context));
            return null;
        }

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            if (_response != null)
                WcfResponseManager.AddWcfResponseData(operationName, _response, _context);
        }

        public object BeforeCall(string operationName, object[] inputs)
        {
            return null;
        }
    }
}
